import pymysql
from dbutils.pooled_db import PooledDB

from python_quant.config.sys_config import MysqlConfig


class SqlHelper:
    # 初始化数据库连接池
    __pool = PooledDB(
        creator=pymysql,  # 使用链接数据库的模块
        maxconnections=20,  # 连接池允许的最大连接数，0和None表示不限制连接数
        mincached=2,  # 初始化时，链接池中至少创建的空闲的链接，0表示不创建
        maxcached=5,  # 链接池中最多闲置的链接，0和None不限制
        blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
        maxusage=None,  # 一个链接最多被重复使用的次数，None表示无限制
        setsession=[],  # 开始会话前执行的命令列表。如：["set datestyle to ...", "set time zone ..."]
        ping=0,
        # ping MySQL服务端，检查是否服务可用。# 如：0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
        host=MysqlConfig.host,
        port=int(MysqlConfig.port),
        user=MysqlConfig.user,
        passwd=MysqlConfig.passwd,
        db=MysqlConfig.db,
        charset='utf8'
    )

    # 获取一个数据库连接
    @classmethod
    def get_conn(cls):
        # 创建连接
        # conn = pymysql.connect(host='192.168.11.38', port=3306, user='root', passwd='apNXgF6RDitFtDQx', db='m2day03db')
        conn = cls.__pool.connection()
        # 创建游标
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        return conn, cursor

    # 关闭游标和数据库连接
    @classmethod
    def close(cls, conn, cursor):
        # 关闭游标
        cursor.close()
        # 关闭连接
        conn.close()

    # 查询一行记录
    @classmethod
    def fetch_one(cls, sql, args):
        conn, cursor = cls.get_conn()
        # 执行SQL，并返回收影响行数
        effect_row = cursor.execute(sql, args)
        result = cursor.fetchone()
        cls.close(conn, cursor)

        return result

    # 查询多行记录
    @classmethod
    def fetch_all(cls, sql, args):
        conn, cursor = cls.get_conn()
        # 执行SQL，并返回收影响行数
        cursor.execute(sql, args)
        result = cursor.fetchall()

        cls.close(conn, cursor)
        return result

    @classmethod
    def update(cls, sql, args):
        effect_row = 0
        conn, cursor = cls.get_conn()
        try:
            # 执行SQL，并返回收影响行数
            effect_row = cursor.execute(sql, args)
            conn.commit()
        finally:
            cls.close(conn, cursor)
        return effect_row

    # 删除记录
    @classmethod
    def delete(cls, sql, args):
        effect_row = 0
        conn, cursor = cls.get_conn()
        try:
            # 执行SQL，并返回收影响行数
            effect_row = cursor.execute(sql, args)
            conn.commit()
        finally:
            cls.close(conn, cursor)
        return effect_row

    # 创建记录
    @classmethod
    def insert(cls, sql, args):
        """
        创建数据
        :param sql: 含有占位符的SQL
        :return:
        """
        effect_row = 0
        conn, cursor = cls.get_conn()
        try:
            # 执行SQL，并返回收影响行数
            effect_row = cursor.execute(sql, args)
            conn.commit()
        finally:
            cls.close(conn, cursor)
        return effect_row


# 使用示例
if __name__ == '__main__':
    sql = 'select id,name,age from user where id=%s'
    args = (4,)
    result = SqlHelper.fetch_one(sql, args)
    print(result)

    '''
    sql = 'insert into user (name, age) values (%s, %s)'
    args = ('zhangsan', '20')
    SqlHelper.insert(sql, args)
    print(result)

    sql = 'update user set name=%s where id=%s'
    args = ('lisi', 1)
    SqlHelper.update(sql, args)
    print(result)


    sql = 'delete from user where id=%s'
    args = (1,)
    SqlHelper.delete(sql, args)
    print(result)
'''
